<template>
  <a-upload
    :data="headers"
    :action="action"
    :before-upload="beforeUpload"
    :maxCount="props.maxCount"
    :multiple="props.multiple"
    list-type="picture-card"
    v-model:file-list="fileList"
    @preview="handlePreview"
    @change="handleChange"
    @remove="handleRemove"
  >
    <div v-if="fileList.length < maxCount">
      <plus-outlined />
      <div style="margin-top: 8px">上传图片</div>
    </div>
  </a-upload>
  <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
    <img alt="这是一张图片" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>
<script setup>
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { onMounted, reactive, ref, defineProps, defineEmits, watch } from 'vue'

import { upload_qiniu } from '../config/api'
import { UPLOAD_URL, QINIU_URL } from '../config/config'

const props = defineProps({
  imgUrl: {
    type: String,
    default: ''
  },
  // imgNum: {
  //   type: Number,
  //   default: 1
  // },
  maxCount: {
    type: Number,
    default: 1
  }, //最大限制几张
  multiple: {
    type: Boolean,
    default: false
  } //是否可以多图上传
})

const emits = defineEmits(['fileimgUrl', 'remove'])

onMounted(() => {
  gettoken()
  // console.log(props.imgUrl)
  // fileList.value = handleData(props.imgUrl)
})

watch(
  () => props.imgUrl,
  newValue => {
    handleData(newValue)
  }
)

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

// 头部token
const headers = reactive({
  token: ''
})
// 请求头
const action = ref(UPLOAD_URL)
// 预览弹窗
const previewVisible = ref(false)
// 预览的图片
const previewImage = ref('')
//预览图片表标题
const previewTitle = ref('')
// 图片列表
let fileList = ref([])
let disabled = ref(false)

// 删除图片
const handleRemove = file => {
  // console.log(file)
  fileList.value.forEach((item, index) => {
    if (item.uid == file.uid) {
      fileList.value.splice(index, 1)
      emits('remove', fileList.value)
    }
  })
}

// 回显图片
const handleData = data => {
  let tem = data.split(',')
  // let list = []
  tem.forEach(item => {
    fileList.value.push({ url: item })
  })
}

//关闭弹窗
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}

// 上传前的规则
const beforeUpload = () => {}

// 上传图片
const handleChange = ({ fileList }) => {
  console.log(fileList)
  if (fileList.length > 1) {
    let imgs = []
    fileList.map(item => {
      if (item.status == 'done') {
        imgs.push(QINIU_URL + item.response.key)
      }
    })
    emits('fileimgUrl', imgs)
  } else if (fileList.length == 1) {
    const status = fileList[0].status
    if (status == 'done') {
      emits('fileimgUrl', QINIU_URL + fileList[0].response.key)
    }
  } else {
    fileList = []
    emits('fileimgUrl', '')
  }
}

//预览图片方法
const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj)
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}

//获取token
const gettoken = async () => {
  const res = await upload_qiniu()
  headers.token = res.data
}
</script>
<style scoped>
</style>
